﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DXApplicationTangche.DTO;
using DXApplicationTangche.UC.标签打印.Service;
using System.IO;
using DXApplicationTangche.service;
using Seagull.BarTender.Print;
using DXApplicationTangche.UC.标签打印.model;
using System.Text.RegularExpressions;
using DXApplicationTangche.Utils;
using DXApplicationTangche.UC.门店出入库.Service;
using DXApplicationTangche.UC.生产计划.生产批生产.service;

namespace DXApplicationTangche.UC.标签打印
{
    public partial class Form吊牌新 : DevExpress.XtraEditors.XtraForm
    {
        private DTOTag DTO套号吊牌一览 = new DTOTag();
        private List<已打印吊牌> 已打印吊牌s = new List<已打印吊牌>();
        public Form吊牌新()
        {
            InitializeComponent();
        }
        private void simpleButton打印_Click(object sender, EventArgs e)
        {
            String inventoryNo = this.textBox水洗标.Text.Trim();
            if (String.IsNullOrWhiteSpace(this.textBox水洗标.Text))
            {
                return;
            }
            this.打印(inventoryNo);
        }
        private Boolean 打印(String inventoryNo) {
            //  查询入库前工序，判断是否能入库
            //  成品检查不扫，吊牌打不出来
            if (!生产批生产Service.checkStockInWipRecord(inventoryNo))
            {
                MessageBox.Show("成品检查未执行，不能打吊牌");
                //  清空
                this.textBox水洗标.Clear();
                this.textBox款名.Clear();
                this.textBox价格.Clear();
                this.DTO套号吊牌一览.batchNo = null;
                this.ActiveControl = this.textBox水洗标;
                return false;
            }
            try
            {
                this.DTO套号吊牌一览 = 标签打印Service.get套号吊牌打印内容ByBarcode(inventoryNo);
                if (String.IsNullOrEmpty(this.DTO套号吊牌一览.batchNo))
                {
                    MessageBox.Show("吊牌信息不存在");
                    return false;
                }
                else
                {
                    this.textBox款名.Text = this.DTO套号吊牌一览.styleNameCn;
                    //  拿到门店的客户套号没有价格也能打吊牌
                    //  仅门店补货未登记样衣是需要登记样衣，填写价格
                    if (!this.DTO套号吊牌一览.mtoInventory)
                    {
                        //  补货判断是否登记样衣
                        if (this.DTO套号吊牌一览.price == 0)
                        {
                            this.textBox价格.Clear();
                            MessageBox.Show("样衣未登记，通知技术科进行登记");
                            return false;
                        }
                        else
                        {
                            this.textBox价格.Text = this.DTO套号吊牌一览.price.ToString();
                        }
                    }
                    else
                    {
                        //  客户套号不需要显示价格
                        this.textBox价格.Text = "0";
                        this.DTO套号吊牌一览.price = 0;
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("无吊牌信息");
                return false;
            }
            //  打印
            this.水洗打印(inventoryNo);
            //  入库
            出入库Service.garmentQCWaitStockIn(inventoryNo);
            //  打印完清空
            this.textBox水洗标.Clear();
            this.textBox款名.Clear();
            this.textBox价格.Clear();
            this.DTO套号吊牌一览.batchNo = null;
            this.ActiveControl = this.textBox水洗标;
            return true;
        }
        private void textBox补打水洗标_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                try
                {
                    if (String.IsNullOrWhiteSpace(this.textBox补打水洗标.Text))
                    {
                        return;
                    }
                    String inventoryNo = this.textBox补打水洗标.Text.Trim();
                    //  查询入库前工序，判断是否能入库
                    //  成品检查不扫，吊牌打不出来
                    if (!生产批生产Service.checkStockInWipRecord(inventoryNo))
                    {
                        MessageBox.Show("成品检查未执行，不能打吊牌");
                        //  清空
                        this.textBox补打水洗标.Clear();
                        return;
                    }
                    this.DTO套号吊牌一览 = 标签打印Service.get套号吊牌打印内容ByBarcode(inventoryNo);
                    if (String.IsNullOrEmpty(this.DTO套号吊牌一览.batchNo))
                    {
                        MessageBox.Show("吊牌信息不存在");
                    }
                    else
                    {
                        if (!this.DTO套号吊牌一览.mtoInventory)
                        {
                            if (this.DTO套号吊牌一览.price == 0)
                            {
                                MessageBox.Show("样衣未登记，通知技术科进行登记");
                                return;
                            }
                        }
                        else
                        {
                            //  客户套号不需要显示价格
                            this.textBox价格.Text = "0";
                            this.DTO套号吊牌一览.price = 0;
                        }
                    }
                    //this.print补打大吊牌(inventoryNo);
                    this.print抖音吊牌(inventoryNo);
                    //  入库
                    出入库Service.garmentQCWaitStockIn(inventoryNo);
                }
                catch (Exception)
                {
                    MessageBox.Show("无吊牌信息");
                    return;
                }
            }
        }
        private void simpleButton批量打印_Click(object sender, EventArgs e)
        {
            //  读取memo数据
            List<String> list = new List<string>(this.memoEdit1.Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries));
            if (list.Count > 0) {
                //  执行打印
                if (this.打印(list[0]))
                {
                    //  如果成功，显示
                    this.已打印吊牌s.Add(new 已打印吊牌(list[0]));
                    this.gridControl1.DataSource = this.已打印吊牌s;
                    this.gridView1.RefreshData();
                    list.Remove(list[0]);
                    this.memoEdit1.Text = string.Join("\n", list.ToArray());
                }
            }
        }
        private void 水洗打印(String inventoryNo)
        {
            //包含字母
            if (Regex.Matches(inventoryNo,"[a-zA-Z]").Count>0)
            {
                this.根据类型获取模板新(inventoryNo, "20210322");
            }
            //不包含字母
            else
            {
                this.根据类型获取模板新(inventoryNo, "code93");
            }
        }
        /// <summary>
        /// 根据类型下载不同模板
        /// </summary>
        /// <param name="inventoryNo">条码</param>
        private void 根据类型获取模板新(String inventoryNo,String suffix)
        {
            //新的客户吊牌
            String filePath客户 = "standardCustomerTag_"+ suffix + "_2.btw";
            String fileName客户 = Path.GetFileName(filePath客户);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印
            if (!System.IO.File.Exists(@"tag\" + fileName客户))
            {
                FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath客户, @"tag\" + fileName客户, -1);
            }

            //留给销售的大吊牌
            //根据类型获取不同模板
            String filePath销售 = this.DTO套号吊牌一览.styleCategoryCd + "_"+ suffix + ".btw";
            String fileName销售 = Path.GetFileName(filePath销售);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印
            if (!System.IO.File.Exists(@"tag\" + fileName销售))
            {
                FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath销售, @"tag\" + fileName销售, -1);
            }
            this.print两种全打(@"tag\" + fileName客户, @"tag\" + fileName销售, inventoryNo);
        }

        /// <summary>
        /// 两种吊牌都打印
        /// </summary>
        /// <param name="file客户"></param>
        /// <param name="file销售"></param>
        /// <param name="inventoryNo"></param>
        private void print两种全打(String file客户, String file销售, String inventoryNo)
        {
            //String PrinterName = "迅捷PDF虚拟打印机";
            String PrinterName = "POSTEK G-3106";
            String str = System.AppDomain.CurrentDomain.BaseDirectory;
            Engine btEngine = new Engine();
            btEngine.Start();
            #region 客户吊牌
            LabelFormatDocument btFormat = btEngine.Documents.Open(str + file客户);
            //指定打印机名 
            btFormat.PrintSetup.PrinterName = PrinterName;
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 
            btFormat.SubStrings["styleNo"].Value = this.DTO套号吊牌一览.styleNameCn.Split(' ')[0];
            btFormat.SubStrings["styleName"].Value = this.DTO套号吊牌一览.styleNameCn.Split(' ')[1];
            btFormat.SubStrings["fabricComposition"].Value = this.DTO套号吊牌一览.materialComposition;
            btFormat.SubStrings["size"].Value = this.DTO套号吊牌一览.styleSizeCd;
            btFormat.SubStrings["price"].Value = "¥" + this.DTO套号吊牌一览.price.ToString();
            btFormat.SubStrings["fabricNumber"].Value = this.DTO套号吊牌一览.materialCode;
            btFormat.SubStrings["inventoryNo"].Value = inventoryNo;

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Result nResult1 = btFormat.Print("套号吊牌" + inventoryNo, waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            #endregion

            #region 销售大吊牌
            LabelFormatDocument btFormat销售 = btEngine.Documents.Open(str + file销售);
            //指定打印机名
            btFormat销售.PrintSetup.PrinterName = PrinterName;
            //打印份数                   
            btFormat销售.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat销售.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 
            if (this.DTO套号吊牌一览.mtoInventory)
            {
                btFormat销售.SubStrings["customerName"].Value = this.DTO套号吊牌一览.customerName;
            }
            else
            {
                btFormat销售.SubStrings["customerName"].Value = "套号/样品补货";
            }
            btFormat销售.SubStrings["styleNo"].Value = this.DTO套号吊牌一览.styleNameCn.Split(' ')[0];
            btFormat销售.SubStrings["styleName"].Value = this.DTO套号吊牌一览.materialCode;
            btFormat销售.SubStrings["price"].Value = "¥" + this.DTO套号吊牌一览.price.ToString();
            btFormat销售.SubStrings["size"].Value = this.DTO套号吊牌一览.styleSizeCd;
            btFormat销售.SubStrings["inventoryNo"].Value = inventoryNo;

            //不同款式类型吊牌打印内容不同
            标签打印Model 标签打印Model = new 标签打印Model().buildDTO套号吊牌s(this.DTO套号吊牌一览.measureItemDTOS);
            foreach (DTO套号吊牌尺寸 dTO in 标签打印Model.DTO套号吊牌s)
            {
                try
                {
                    btFormat销售.SubStrings[dTO.吊牌项目].Value = dTO.成衣值;
                }
                catch { }
            }

            int waitout2 = 10000; // 10秒 超时 
            Result nResult2 = btFormat销售.Print("套号销售吊牌条码" + inventoryNo, waitout2, out messages);
            btFormat销售.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改
            btFormat销售.Close(SaveOptions.DoNotSaveChanges);
            #endregion
            //结束打印引擎                  
            btEngine.Stop();
            this.textBox水洗标.Clear();
            this.textBox补打水洗标.Clear();
        }

        /// <summary>
        /// print补打大吊牌
        /// </summary>
        /// <param name="file销售"></param>
        /// <param name="inventoryNo"></param>
        private void print补打大吊牌(String inventoryNo)
        {
            //留给销售的大吊牌
            //根据类型获取不同模板
            String filePath销售 = this.DTO套号吊牌一览.styleCategoryCd + "_20210322.btw";
            String fileName销售 = Path.GetFileName(filePath销售);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印
            if (!System.IO.File.Exists(@"tag\" + fileName销售))
            {
                FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath销售, @"tag\" + fileName销售, -1);
            }
            String str = System.AppDomain.CurrentDomain.BaseDirectory;
            Engine btEngine = new Engine();
            btEngine.Start();
            #region print补打大吊牌
            LabelFormatDocument btFormat = btEngine.Documents.Open(str + @"tag\" + fileName销售);
            //指定打印机名 
            //btFormat.PrintSetup.PrinterName = "迅捷PDF虚拟打印机";
            btFormat.PrintSetup.PrinterName = "POSTEK G-3106";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 
            if (this.DTO套号吊牌一览.mtoInventory)
            {
                btFormat.SubStrings["customerName"].Value = this.DTO套号吊牌一览.customerName;
            }
            else
            {
                btFormat.SubStrings["customerName"].Value = "套号/样品补货";
            }
            btFormat.SubStrings["styleNo"].Value = this.DTO套号吊牌一览.styleNameCn.Split(' ')[0];
            btFormat.SubStrings["styleName"].Value = this.DTO套号吊牌一览.materialCode;
            btFormat.SubStrings["price"].Value = "¥" + this.DTO套号吊牌一览.price.ToString();
            btFormat.SubStrings["size"].Value = this.DTO套号吊牌一览.styleSizeCd;
            btFormat.SubStrings["inventoryNo"].Value = inventoryNo;

            //不同款式类型吊牌打印内容不同
            标签打印Model 标签打印Model = new 标签打印Model().buildDTO套号吊牌s(this.DTO套号吊牌一览.measureItemDTOS);
            foreach (DTO套号吊牌尺寸 dTO in 标签打印Model.DTO套号吊牌s)
            {
                try
                {
                    btFormat.SubStrings[dTO.吊牌项目].Value = dTO.成衣值;
                }
                catch { }
            }
            Messages messages;
            int waitout2 = 10000; // 10秒 超时 
            Result nResult2 = btFormat.Print("套号销售吊牌条码" + inventoryNo, waitout2, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
            #endregion
            this.textBox补打水洗标.Clear();
        }

        private void print抖音吊牌(String inventoryNo)
        {
            //新的客户吊牌
            String filePath客户 = "standardCustomerTag_code93_2.btw";
            String fileName客户 = Path.GetFileName(filePath客户);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印
            if (!System.IO.File.Exists(@"tag\" + fileName客户))
            {
                FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath客户, @"tag\" + fileName客户, -1);
            }
            String str = System.AppDomain.CurrentDomain.BaseDirectory;
            Engine btEngine = new Engine();
            btEngine.Start();

            #region 客户吊牌
            LabelFormatDocument btFormat = btEngine.Documents.Open(str + @"tag\" + fileName客户);
            //指定打印机名 
            //btFormat.PrintSetup.PrinterName = "迅捷PDF虚拟打印机";
            btFormat.PrintSetup.PrinterName = "POSTEK G-3106";
            //btFormat.PrintSetup.PrinterName = "Microsoft Print to PDF";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 
            btFormat.SubStrings["styleNo"].Value = this.DTO套号吊牌一览.styleNameCn.Split(' ')[0];
            btFormat.SubStrings["styleName"].Value = this.DTO套号吊牌一览.styleNameCn.Split(' ')[1];
            btFormat.SubStrings["fabricComposition"].Value = this.DTO套号吊牌一览.materialComposition;
            btFormat.SubStrings["size"].Value = this.DTO套号吊牌一览.styleSizeCd;
            btFormat.SubStrings["price"].Value = "¥" + this.DTO套号吊牌一览.price.ToString();
            btFormat.SubStrings["fabricNumber"].Value = this.DTO套号吊牌一览.materialCode;
            btFormat.SubStrings["inventoryNo"].Value = inventoryNo;

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Result nResult1 = btFormat.Print("抖音吊牌" + inventoryNo, waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
            #endregion
            this.textBox补打水洗标.Clear();
        }
    }

    class 已打印吊牌
    {
        public String barcode { get; set; }
        public DateTime dateTime { get; set; }

        public 已打印吊牌(String barcode)
        {
            this.barcode = barcode;
            this.dateTime = DateTime.Now;
        }
    }
}